from flask import Flask, render_template, request

from 数据抓取检查模块 import Data_catcher
from 图表生成模块 import Frame_editor


app = Flask(__name__, static_folder="templates")
film_search_list = {}
frame_editor_list = {}
working_state = {}


@app.route("/", methods=["GET"])
def index():
    real_ip = request.headers['X-Forwarded-For']
    film_search_list[real_ip] = ".!.?-548^&"
    working_state[real_ip] = 0
    return render_template("homepage.html")


@app.route("/filmdataframe/<string:filmname>", methods=["GET"])
def get_film_frame(filmname):
    real_ip = request.headers['X-Forwarded-For']
    if working_state.get(real_ip) is None:
        return render_template("nosearchdata.html")
    elif film_search_list[real_ip] == filmname:
        return render_template("index.html")
    elif working_state[real_ip] == 0:
        working_state[real_ip] = 1
        data_catcher = Data_catcher(filmname)
        if data_catcher.film_cid is not None:
            data_catcher.set_barrage_dataset()
            frame_editor = Frame_editor()
            time_data_about = data_catcher.get_barrage_time_data()
            frame_editor.create_line_chart(time_data_about[0], time_data_about[1], data_catcher.film_name)
            frame_editor.create_wordcloud_chart(data_catcher.get_barrage_ranking())
            frame_editor_list[real_ip] = frame_editor
            film_search_list[real_ip] = filmname
            working_state[real_ip] = 0
            return render_template("index.html")
        else:
            working_state[real_ip] = 0
            return render_template("nofound.html")
    else:
        return render_template("wait.html")

@app.route("/index/linechart")
def linechart():
    return frame_editor_list[request.headers['X-Forwarded-For']].line_chart.dump_options_with_quotes()

@app.route("/index/wordcloudchart")
def wordcloudchart():
    return frame_editor_list[request.headers['X-Forwarded-For']].wordcloud_chart.dump_options_with_quotes()


app.run(host='127.0.0.1', port=4000, processes=True)
